package com.lzh.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.lzh.oss.service.FileService;
import com.lzh.oss.utils.ConstantPropertiesUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author lzhstart
 * @create 2021/4/22 16:13
 */
@Service
public class FileServiceImpl implements FileService {


    @Override
    public String uploadAvatar(MultipartFile file) {
        //获取oss相关配置
        String endPoint = ConstantPropertiesUtil.END_POINT;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        String url = null;
        //上传文件到oss
        try {
            OSSClient ossClient = new OSSClient(endPoint, accessKeyId, accessKeySecret);
            //获取上传文件流
            InputStream inputStream = file.getInputStream();
            //获取文件名
            String filename = file.getOriginalFilename();
            //获取文件名后缀
            String prefix = filename.substring(filename.lastIndexOf("."));
            //将生成的uuid的-替换
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            //使用uuid生成唯一的文件名
            String newFilename = uuid + prefix;
            ossClient.putObject(bucketName, newFilename,inputStream);
            ossClient.shutdown();
            url = "https://"+bucketName+"."+endPoint+"/"+newFilename;
            return url;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 删除图片
     * @param filePath
     */
    @Override
    public void deleteAvatar(String filePath) {
        //获取oss相关配置
        String endPoint = ConstantPropertiesUtil.END_POINT;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        // 创建OSSClient实例。
        OSSClient ossClient = new OSSClient(endPoint, accessKeyId, accessKeySecret);
        // 删除文件。如需删除文件夹，请将ObjectName设置为对应的文件夹名称。如果文件夹非空，则需要将文件夹下的所有object删除后才能删除该文件夹。
        ossClient.deleteObject(bucketName, filePath);
        // 关闭OSSClient。
        ossClient.shutdown();
    }
}
